import { useEffect, useState, useRef } from 'react'
import styles from './index.module.scss'
import Input from './input'
import Button from '../button'
import { useCountDown } from '@/utils/hooks'
import { checkCodeValid, sendCode } from '@/api/login'

const Index = props => {
  const { setType, email: medium, code, setCode } = props
  const [error, setError] = useState(false)
  const submitRef = useRef(null)
  const inputRef = useRef()
  const [endtime, passed, startCount] = useCountDown(60)
  const nextStep = async () => {
    const res = await checkCodeValid({ medium, code })
    if (res.code) {
      setError(true)
      return
    }
    setType('reset_pwd')
  }

  const regetCode = async () => {
    await sendCode(medium)
    startCount()
  }

  useEffect(() => {
    const enterClick = e => {
      if (e.keyCode === 13) {
        submitRef.current.click()
      }
    }
    startCount()
    inputRef.current.focus()
    window.addEventListener('keydown', enterClick)
    return () => {
      window.removeEventListener('keydown', enterClick)
    }
  }, [])

  return (
    <div className={styles.regetPwd}>
      <p className={styles.p}>已发送验证码到邮箱：<span className='text-theme'>{medium}</span></p>
      <p className={styles.p}>请注意查收，该验证码15分钟内有效</p>
      <Input
        placeholder="请输入验证码"
        type="text"
        ref={inputRef}
        className={styles.code}
        onChange={data => setCode(data)}
      />
      <Button hover="opacity" ref={submitRef} className={styles.btn} onClick={nextStep}>
        下一步
      </Button>
      {error ? <p className={styles.error}>验证码错误</p> : null}
      <p className={styles.noget}>
        {passed ? (
          <span>验证码已重新发送，{endtime}s后可重发</span>
        ) : (
          <>
            <span>没有收到验证码？</span>
            <span className={styles.reSend} onClick={regetCode}>
              点这重发
            </span>
          </>
        )}
      </p>
    </div>
  )
}

export default Index
